package com.atguigu.service.impl;

import com.atguigu.dao.BookDao;
import com.atguigu.dao.OrderDao;
import com.atguigu.dao.OrderItemDao;
import com.atguigu.dao.impl.BookDaoImpl;
import com.atguigu.dao.impl.OrderDaoImpl;
import com.atguigu.dao.impl.OrderItemDaoImpl;
import com.atguigu.pojo.*;
import com.atguigu.service.BookService;
import com.atguigu.service.OrderService;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

public class OrderServiceImpl implements OrderService {
private OrderItemDao orderItemDao = new OrderItemDaoImpl();
private OrderDao orderDao = new OrderDaoImpl();
private BookDao bookDao = new BookDaoImpl();
    @Override
    public String creatOrder(Cart cart, Integer userId) {
//        创建订单的唯一性
        String OrderId = System.currentTimeMillis() + "" + userId;
//        创建一个订单对象
        Order order = new Order(OrderId ,new Date(),cart.getTotalPrice(),0,userId);
//       调用saveOrder方法保存订单对象
        orderDao.saveOrder(order);

        int i = 12/0;
//        遍历购物车中的每个商品项转换为订单项保存到数据库
for (Map.Entry<Integer, CartItem> entry:cart.getItems().entrySet()){
CartItem cartItem = entry.getValue();
    OrderItem orderItem = new OrderItem(null,cartItem.getName(),cartItem.getCount(),cartItem.getPrice(),cartItem.getTotalPrice(),OrderId);


//    保存订单项到数据库
    orderItemDao.saveOrderItem(orderItem);

    Book book = bookDao.queryBookById(cartItem.getId());
    book.setSales(book.getStock()+ cartItem.getCount());
    book.setStock(book.getStock()- cartItem.getCount());
    bookDao.updatebook(book);
}
//清空购物车
        cart.clear();
return OrderId;
    }
}
